<?php
require dirname(__FILE__).'/core/fanwe.php';
$fanwe = &FanweService::instance();
$fanwe->initialize();

$index = intval($_REQUEST['index']);
@set_time_limit(0);
if(function_exists('ini_set'))
    ini_set('max_execution_time',0);

$limit = 50;

$list = FDB::fetchAll('SELECT share_id,cache_data FROM '.FDB::table('share')." WHERE share_data IN ('goods','photo','goods_photo') ORDER BY share_id DESC LIMIT ".$index.','.$limit);
if(count($list) == 0)
{
	echo "<h1>更新会员图片完成</h1>";
	exit;
}

$res = FDB::query('SELECT * FROM '.FDB::table('share_image_sizes').' WHERE status = 1');
while($data = FDB::fetch($res))
{
	$size_key = $data['width'].'x'.$data['height'];
	$size_setting[$size_key] = array($data['width'],$data['height'],$data['is_cut'],$data['is_water']);
}

function getImgSizeName($url)
{
	$arr = explode('_',$url);
	$arr = explode('.',$arr[1]);
	return $arr[0];
}

foreach($list as $data)
{
	$cache_data = unserialize($data['cache_data']);
	$imgs = $cache_data['imgs'];

	$old_imgs = array();
	foreach($imgs['all'] as $img)
	{
		$old_imgs[] = FANWE_ROOT.str_replace('./','',$img['img']);
	}

	$key = getDirsById($data['share_id']);
	$share_dir = FANWE_ROOT.'public/upload/share/'.$key.'/';

	if($dirhandle = opendir($share_dir))
	{
		while(($file = readdir($dirhandle)) !== FALSE)
		{
			if(($file!=".") && ($file!=".."))
			{
				$filename = $share_dir.$file;
				if(array_search($filename,$old_imgs) === FALSE)
				{
					$img_size = getImgSizeName($filename);
					if(!isset($size_setting[$img_size]))
					{
						@unlink($filename);
					}
				}
			}
		}
		@closedir($dirhandle);
		usleep(20);

		foreach($old_imgs as $old_img)
		{
			$old_img = str_replace(FANWE_ROOT,'',$old_img);
			foreach($size_setting as $size)
			{
				getImgName($old_img,$size[0],$size[1],$size[2]);
				usleep(5);
			}
		}
	}

    echo "更新 $data[share_id] 图片成功<br/>";
	flush();
	ob_flush();
    usleep(10);
}

echo "<script type=\"text/javascript\">var fun = function(){location.href='update_share.php?index=".($index + $limit)."&time=".time()."';}; setTimeout(fun,1000);</script>"."\r\n";
flush();
ob_flush();
exit;
?>